package com.growthserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.growthserver.entity.*;
import com.growthserver.mapper.AppletMapper;
import com.growthserver.mapper.IntegralGrowthMapper;
import com.growthserver.param.CommonParam;
import com.growthserver.param.IntegralParam;
import com.growthserver.service.AppletService;
import com.growthserver.service.TaskRuleVerificationService;
import com.growthserver.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AppletServiceImpl implements AppletService {

    private final Logger LOGGER = LoggerFactory.getLogger(AppletService.class);


    @Autowired
    private AppletMapper appletMapper;

    @Autowired
    private IntegralGrowthMapper integralGrowthMapper;

    @Autowired
    private TaskRuleVerificationService taskRuleVerificationService;

    /**
     * 单位天 整形
     */
    @Value("${expDays}")
    private String expDays;


    @Override
    @Transactional
    public void memberRegistration(String userId, String userName) {
        LOGGER.info("測試");
        //查询userId是否存在
        TMemberEntity tMemberEntity = appletMapper.selectMemberInfoByUserId(userId);
        if (tMemberEntity == null) {
            // 获取会员等级创建枚举
            HashMap<String, String> memberLevelEnum = appletMapper.getMemberLevelEnum();
            String levelNum = memberLevelEnum.get("levelNum");
            String levelName = memberLevelEnum.get("levelName");
            //默认 自动注册有效期为1年
            //会员信息注册
            String memberId = String.valueOf(new Date().getTime());
            appletMapper.memberRegistration(userId, userName, levelNum, levelName,memberId);
            IntegralParam integralParam = new IntegralParam();
            integralParam.setUserId(userId);
            integralParam.setType(RuleTypeEnum.ZC.getCode());
            taskRuleVerificationService.ruleVerification(integralParam);
            LOGGER.info("用户会员绑定成功");
        } else {
            LOGGER.info("用户会员信息存在,用户会员ID:{}", tMemberEntity.getMemberId());
        }
    }

    @Override
    public void memberLogOff(String userId) {
        appletMapper.deleteMemberByUserId(userId);
    }

    @Override
    public void updateUserType(String userId, String userType) {
        appletMapper.updateUserType(userId, userType);
    }

    /**
     * 获取用户 等级,总成长值,总积分
     */
    @Override
    public TMemberEntity getUserLevel(String userId) {
        return appletMapper.getUserLevel(userId);
    }

    @Override
    public List<HashMap<String, String>> getUserLevelList(List<String> userIds) {
        return appletMapper.getUserLevelList(userIds);
    }

    /**
     * 获取用户成长值明细
     */
    @Override
    public List<TIntegralInfo> getUserGrowth(CommonParam commonParam) {
        PageHelper.startPage(commonParam.getPageNo(), commonParam.getPageSize());
        return appletMapper.getUserGrowth(commonParam);
    }

    @Override
    public String getTotalGrowthValue(String userId) {
        TMemberEntity userLevel = appletMapper.getUserLevel(userId);
        return userLevel.getTotalGrowthValue();
    }


    /**
     * 获取用户等级对应权益
     */
    @Override
    public Object getUserLevelEquity(String userId) {
        // 获取用户会员信息
        TMemberEntity userLevel = appletMapper.getUserLevel(userId);
        //获取用户类型所有权益
        List<TMemberEquityEntity> userEquity = appletMapper.getUserAllEquity(userLevel.getUserType());
        //根据成长值进行过滤 用户获取最小成长值权益
        userEquity.forEach(tMemberEquityEntity -> {
            int minGrowthValue = Integer.parseInt(tMemberEquityEntity.getMinGrowthValue());
            int totalGrowthValue = Integer.parseInt(userLevel.getTotalGrowthValue());
            tMemberEquityEntity.setDisplayStatus(minGrowthValue <= totalGrowthValue ? 1 : 0);
        });
        return userEquity;
    }

    @Override
    public Object equityGrowthSliding(String userId) {
        TMemberEntity userLevel = appletMapper.getUserLevel(userId);
        //查询等级表获取当前等级和成长值
        String memberLevel = userLevel.getMemberLevel();
        String totalGrowthValue = userLevel.getTotalGrowthValue();
        //获取等级 成长值列表
        List<TMemberLevelEntity> tMemberLevelEntities = integralGrowthMapper.selectALLEquityGrowth(userLevel.getUserType());
        ArrayList<Object> array = new ArrayList<>();
        for (TMemberLevelEntity tMemberLevelEntity : tMemberLevelEntities
        ) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("memberLevel", tMemberLevelEntity.getMemberLevel());
            map.put("levelName", tMemberLevelEntity.getLevelName());
            map.put("totalGrowthValue", totalGrowthValue);
            //如果大于当前等级值的,取最大值,否则去最大值
            if (Integer.parseInt(memberLevel) > Integer.parseInt(tMemberLevelEntity.getMemberLevel())) {
                map.put("growth", tMemberLevelEntity.getMaxGrowthValue());
                map.put("index", 0);
            } else if (Integer.parseInt(memberLevel) == Integer.parseInt(tMemberLevelEntity.getMemberLevel())) {
                map.put("growth", tMemberLevelEntity.getMaxGrowthValue());
                map.put("index", 1);
            } else {
                map.put("growth", tMemberLevelEntity.getMinGrowthValue());
                map.put("index", 0);
            }
            array.add(map);
        }
        return array;
    }


    /**
     * 获取用户积分明细
     */
    @Override
    public List<TIntegralInfo> getUserIntegral(CommonParam commonParam) {
        PageHelper.startPage(commonParam.getPageNo(), commonParam.getPageSize());
        return appletMapper.getUserIntegral(commonParam);
    }


    /**
     * 获取用户过期积分
     */
    @Override
    public String getWillExpIntegral(String userId) {
        return appletMapper.getWillExpIntegral(userId, expDays);
    }

    /**
     * 获取用户总积分
     */
    @Override
    public String getTotalIntegral(String userId) {
        TMemberEntity userLevel = appletMapper.getUserLevel(userId);
        return userLevel.getTotalIntegralValue();
    }


    /**
     * 对外调用接口  被动
     * 签到,点赞,抽奖.....
     */
    @Override
    public List<HashMap<String, String>> growthRules(IntegralParam integralParam) {
        LOGGER.info("用户:{}", "类型:{}", integralParam.getUserId(), integralParam.getType());
        //调用积分计算规则
        return taskRuleVerificationService.ruleVerification(integralParam);
    }

    /**
     * @param integralParam
     * @return
     */
    @Override
    public List<TTaskRuleEntity> taskRuleInActiveTime(IntegralParam integralParam) {
        TMemberEntity tMemberEntity = appletMapper.selectMemberInfoByUserId(integralParam.getUserId());
        //获取 会员等级查询
        return appletMapper.getTaskRuleByType(integralParam.getTaskType(), tMemberEntity.getLevelNum());
    }

    @Override
    public List<HashMap<String, String>> getIntegralBudgetNo(IntegralParam integralParam) {
        return appletMapper.getIntegralBudgetNo(integralParam);
    }

    @Override
    public void integralBudgetRelease(IntegralParam integralParam) {
        appletMapper.integralBudgetRelease(integralParam.getBudgetRequestNum());
    }

    @Override
    public int getIntegralBudgetNoIntegral(IntegralParam integralParam) {
        //查询单号总积分
        int integralBudgetNoTotalIntegral = appletMapper.getIntegralBudgetNoTotalIntegral(integralParam);
        //使用积分
        int integralBudgetNoIntegral = appletMapper.getIntegralBudgetNoIntegral(integralParam);
        return integralBudgetNoTotalIntegral - integralBudgetNoIntegral;

    }

    @Override
    public List<Object> signInSquare(IntegralParam integralParam) {
        LOGGER.info("测试");
        List<Object> arrayList = new ArrayList<>();
        //获取用户等级
        TMemberEntity memberEntity = getUserLevel(integralParam.getUserId());
        //通过 用户等级,用户类型 当前时间 参数, 获取对应规则模板
        List<TTaskRuleDetailEntity> tIovTaskRuleDetails = integralGrowthMapper.selectByMouldAndUserType(memberEntity.getUserType(),
                memberEntity.getLevelNum(), integralParam.getType());
        //过滤
        List<TTaskRuleDetailEntity> filteredList = tIovTaskRuleDetails.stream()
                .filter(p -> p.getIsContinuous().equals("1"))
                .collect(Collectors.toList());
        //通过规则模板,获取对应日志条数
        for (TTaskRuleDetailEntity tTaskRuleDetailEntity : filteredList
        ) {
            tTaskRuleDetailEntity.setCreator(integralParam.getUserId());
            // 拿到活动时间内所有,task_rule_ID,查询所有
            List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities = appletMapper.selectContinuity(integralParam.getUserId(), tTaskRuleDetailEntity.getTaskRuleId());
            //从活动开始到 到现在是否有断续时间
            String taskStartTime = tTaskRuleDetailEntity.getTaskStartTime();
            int index = getDate(tTaskRuleDoRecordEntities, taskStartTime);
            //目标天数
            int continuousDays = Integer.parseInt(tTaskRuleDetailEntity.getContinuousDays());
            int targetDays = index > continuousDays ? continuousDays - index % continuousDays : continuousDays - index;
            HashMap<String, Object> map = new HashMap<>();
            //查询日志,判断是否连续
            map.put("continuousDays", Integer.parseInt(tTaskRuleDetailEntity.getContinuousDays()) - targetDays);
            map.put("targetDays", tTaskRuleDetailEntity.getContinuousDays());
            map.put("activeId", tTaskRuleDetailEntity.getActiveId());
            map.put("activeTypeCode", tTaskRuleDetailEntity.getActiveTypeCode());
            map.put("linkUrl", tTaskRuleDetailEntity.getLinkUrl());
            map.put("remainingDays", String.valueOf(targetDays));
            //任务规则ID
            map.put("taskRuleId", tTaskRuleDetailEntity.getTaskRuleId());
            arrayList.add(map);
        }
        return arrayList;
    }

    private int getDate(List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities, String taskStartTime) {
        int index = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            int daysDifference = (int) ((new Date().getTime() - simpleDateFormat.parse(taskStartTime).getTime()) / (24 * 60 * 60 * 1000));
            Date startDate = simpleDateFormat.parse(taskStartTime);
            for (int i = 0; i < daysDifference+1; i++, index++) {
                //活动开始时间在当前时间之前
                if (startDate.before(new Date()) || startDate.getTime() == new Date().getTime()) {
                    // 转 LocalTime类型
                    if (tTaskRuleDoRecordEntities.size() > index) {
                        TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = tTaskRuleDoRecordEntities.get(index);
                        if (tTaskRuleDoRecordEntity == null) {
                            return index;
                        }
                        String createdDate = tTaskRuleDoRecordEntities.get(index).getCreatedDate();
                        Date datedDate = simpleDateFormat.parse(createdDate);
                        Date dayMin = simpleDateFormat.parse(DateUtils.getMin(-i));
                        Date dayMax = simpleDateFormat.parse(DateUtils.getMax(-i));
                        if (dayMin.before(datedDate) && dayMax.after(datedDate)) {
                            continue;
                        } else {
                            //不连续,默认设置为0
                            index = 0;
                            return index;
                        }
                    } else {
                        return index;
                    }
                } else {
                    // 不在活动范围内,默认 0
                    index = 0;
                    return index;
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return index;
    }

    @Override
    public List<TMemberEntity> selectMembersByLevel(IntegralParam integralParam) {
        return appletMapper.selectMembersByLevel(integralParam);
    }
}
